<template>
    <div>
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
          <div ref="main" style="width: 600px;height: 600px;"></div>
        </el-col>
        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
          <div ref="main1" style="width: 600px;height: 600px;"></div>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
          <div ref="main2" style="width: 700px;height: 600px;"></div>
        </el-col>
        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
          <div ref="main3" style="width: 800px;height: 600px;"></div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
          <div ref="main4" style="width: 1000px;height: 700px;"></div>
        </el-col>
      </el-row>
    </div>
</template>

<script>
import * as echarts from 'echarts';
import chinaJson from '@/assets/geojson/china.json'; // 引入中国地图 GeoJSON 数据
import {getDeptEmpCount} from "../api/cinema/emp";
import {countItemsBudgetByYearAndType, countItemsByStatus, countItemsByType} from "../api/item/item";
import {countActorsByNativeplace} from "../api/cinema/actor";

export default {
  data() {
    return {
      statusCounts: [],
      budgetTrends: [],
      typeCounts: [],
      nativePlaceCounts: []
    };
  },
  mounted() {
    this.initDeptEmpCountChart();
    this.initItemStatusChart();
    this.initBudgetTrendChart();
    this.initItemTypeCountChart();
    this.initNativeplaceCountChart();
  },
  methods: {
    initItemStatusChart() {
      countItemsByStatus().then(response => {
        this.statusCounts = response.data;
        const chart = echarts.init(this.$refs.main);
        const option = {
          title: {
            text: '项目状态占比',
            left: 'center'
          },
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
          },
          legend: {
            orient: 'vertical',
            left: 'left'
          },
          series: [
            {
              name: '状态',
              type: 'pie',
              radius: '50%',
              data: this.statusCounts.map(item => ({
                name: item.status,
                value: item.count
              })),
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              },
              label: {
                show: true,
                formatter: '{b}: {c} ({d}%)'
              }
            }
          ]
        };
        chart.setOption(option);
      });
    },

    initBudgetTrendChart() {
      countItemsBudgetByYearAndType().then(response => {
        this.budgetTrends = response.data;

        // 获取当前年份
        const currentYear = new Date().getFullYear();
        // 获取近五年的年份范围
        const recentYears = Array.from({length: 5}, (_, i) => currentYear - i).sort((a, b) => a - b);

        // 过滤出近五年的数据
        const filteredData = this.budgetTrends.filter(item => recentYears.includes(item.year));

        // 获取唯一的年份和类型
        const years = Array.from(new Set(filteredData.map(item => item.year))).sort((a, b) => a - b);
        const types = Array.from(new Set(filteredData.map(item => item.type)));

        // 生成 series 数据
        const series = types.map(type => ({
          name: type,
          type: 'line',
          data: years.map(year => filteredData.find(item => item.year === year && item.type === type)?.budget || 0)
        }));

        // 初始化图表
        const chart = echarts.init(this.$refs.main1);
        const option = {
          title: {
            text: '各类型剧目预算变化趋势',
            left: 'center'
          },
          tooltip: {
            trigger: 'axis',
            formatter: function (params) {
              let tooltip = '';
              params.forEach(param => {
                tooltip += `${param.seriesName}: ${param.value / 10000} 万<br/>`;
              });
              return tooltip;
            }
          },
          legend: {
            data: types,
            orient: 'horizontal', // 水平排列
            bottom: 10 // 放置在图表下方
          },
          xAxis: {
            type: 'category',
            data: years,
            axisLabel: {
              formatter: function (value) {
                return `${value}`;
              }
            },
            name: '年份 (年)',
            nameLocation: 'middle', // 置于 X 轴的最右方
            nameGap: 30
          },
          yAxis: {
            type: 'value',
            axisLabel: {
              formatter: function (value) {
                return `${value / 10000}`;
              }
            },
            name: '预算 (万)',
            nameLocation: 'middle', // 置于 Y 轴的顶部
            top: 0,
            nameGap: 30
          },
          series: series
        };

        chart.setOption(option);
      });
    },

    initItemTypeCountChart() {
      countItemsByType().then(response => {
        this.typeCounts = response.data;
        const chart = echarts.init(this.$refs.main2);
        const option = {
          title: {
            text: '各类型剧目数量',
            left: 'center'
          },
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            orient: 'vertical',
            left: 'left'
          },
          xAxis: {
            type: 'category',
            data: this.typeCounts.map(item => item.type)
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              name: '数量',
              type: 'bar',
              data: this.typeCounts.map(item => item.count),
              label: {
                show: true,
                position: 'top', // 显示在柱子顶部
                formatter: '{c}' // 显示数值
              }
            }
          ]
        };

        chart.setOption(option);
      });
    },

    initDeptEmpCountChart() {
      getDeptEmpCount().then(response => {
        const data = response.data;
        const deptName = data.map(item => item.deptName);
        const dcounts = data.map(item => item.dcounts);
        const deptEmpCount = echarts.init(this.$refs.main3);
        deptEmpCount.setOption({
          title: {
            text: '各部门人数统计',
            left: 'center'
          },
          tooltip: {},
          xAxis: {
            data: deptName
          },
          yAxis: {},
          series: [
            {
              name: '人数',
              type: 'bar',
              data: dcounts,
              label: {
                show: true,
                position: 'top', // 显示在柱子顶部
                formatter: '{c}' // 显示数值
              }
            }
          ]
        });
      });
    },

    async initNativeplaceCountChart() {
      // 注册中国地图
      echarts.registerMap('china', chinaJson);

      try {
        const response = await countActorsByNativeplace();
        console.log('API Response:', response.data); // 输出 API 返回的数据，便于调试

        this.nativePlaceCounts = response.data;

        // 检查数据格式是否符合预期
        if (!Array.isArray(this.nativePlaceCounts) || this.nativePlaceCounts.length === 0) {
          console.error('Invalid or empty data received from API');
          return;
        }

        const chart = echarts.init(this.$refs.main4);
        const option = {
          title: {
            text: '艺人按籍贯分布',
            left: 'center'
          },
          tooltip: {
            trigger: 'item',
            formatter: function (params) {
              return `${params.name}: ${params.value} 人`;
            }
          },
          visualMap: {
            min: 0,
            max: 10, // 根据实际情况调整最大值
            left: 'left',
            top: 'bottom',
            text: ['高', '低'],
            calculable: true
          },
          series: [
            {
              name: '籍贯',
              type: 'map',
              map: 'china',
              roam: true,
              label: {
                show: true
              },
              data: this.nativePlaceCounts.map(item => ({
                name: item.name || '未知', // 处理可能的 null 或 undefined
                value: item.value || 0 // 处理可能的 null 或 undefined
              }))
            }
          ]
        };

        chart.setOption(option);
      } catch (error) {
        console.error('Error fetching data from API:', error);
      }
    }
  }
};
</script>
